package com.youth.youthservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youth.commonutils.R;
import com.youth.commonutils.UserDto;
import com.youth.servicebase.exceptionhandler.GlobalException;
import com.youth.youthservice.client.MemberClient;
import com.youth.youthservice.entity.EduCourse;
import com.youth.youthservice.entity.EduCourseCollect;
import com.youth.youthservice.entity.vo.CourseVo.CourseCollectVo;
import com.youth.youthservice.mapper.EduCourseCollectMapper;
import com.youth.youthservice.service.EduCourseCollectService;
import com.youth.youthservice.service.EduCourseService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

import static com.youth.commonutils.JwtUtils.APP_SECRET;

/**
 * 课程收藏(EduCourseCollect)表服务实现类
 *
 * @author CM
 * @since 2023-05-05 13:08:01
 */
@Service("eduCourseCollectService")
public class EduCourseCollectServiceImpl extends ServiceImpl<EduCourseCollectMapper, EduCourseCollect> implements EduCourseCollectService {

    @Autowired
    private MemberClient memberClient;

    @Autowired
    private EduCourseService eduCourseService;

    /*用户登陆后检查课程是否已经被收藏*/
    @Override
    public R checkCollect(String courseId, HttpServletRequest request) {
        String userId = parseToken2UserId(request);
        /*调用远程方法来请求用户信息*/
        UserDto user = memberClient.getLoginInfo(userId);
        if (user == null) {
            throw new GlobalException(20003, "尚未登录~");
        }
        /*封装请求并查询*/
        LambdaQueryWrapper<EduCourseCollect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EduCourseCollect::getCourseId, courseId)
                .eq(EduCourseCollect::getMemberId, user.getUserId());
        /*检查是否收藏过该课程*/
        int count = count(queryWrapper);
        return R.ok().data("count", count);

    }

    /*收藏课程*/
    @Override
    public R collect(String courseId, HttpServletRequest request) {
        if (StringUtils.isEmpty(courseId)) {
            throw new GlobalException(20003, "课程不存在,无法收藏");
        }
        String userId = parseToken2UserId(request);
        /*调用远程方法获取用户信息*/
        UserDto user = memberClient.getLoginInfo(userId);
        /*封装属性*/
        EduCourseCollect courseCollect = new EduCourseCollect();
        courseCollect.setCourseId(courseId);
        courseCollect.setMemberId(user.getUserId());
        courseCollect.setTeacherId(baseMapper.getTeacherIdByCourseId(courseId));
        /*保存到数据库*/
        boolean save = save(courseCollect);
        if (save) return R.ok();
        else return R.error();
    }

    /*个人中心查询我的收藏*/
    @Override
    public R listByUserId(Long pageNum, Long pageSize, HttpServletRequest request) {
        /*解析token获得用户id*/
        String userId = parseToken2UserId(request);
        /*根据用户id查询出对应的课程id和收藏id*/
        List<CourseCollectVo> courseCollectVos = baseMapper.courseCollectList(userId);
        return R.ok().data("items", courseCollectVos)
                .data("current", pageNum)
                .data("pages", pageNum)
                /*判断是否大于当前页大小，如果大于则去pageSize*/
                .data("size", courseCollectVos.size() > pageSize ? pageSize : courseCollectVos.size())
                .data("total", courseCollectVos.size() > pageSize ? pageSize : courseCollectVos.size())
                .data("hasNext", courseCollectVos.size() > pageSize);
    }

    /*取消课程收藏*/
    @Override
    public R CollectCancel(String courseId, HttpServletRequest request) {
        if (StringUtils.isEmpty(courseId)) {
            throw new GlobalException(20003, "课程不存在~");
        }
        String userId = parseToken2UserId(request);
        /*封装查询条件并删除课程收藏*/
        LambdaQueryWrapper<EduCourseCollect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EduCourseCollect::getMemberId, userId)
                .eq(EduCourseCollect::getCourseId, courseId);
        if (remove(queryWrapper)) return R.ok().message("取消收藏成功");
        else return R.error().message("取消收藏失败");
    }

    @Override
    public R cancel(String id) {
//        根据id直接删除课程，走索引
        removeById(id);
        return R.ok();
    }

    /*设置置顶*/
    @Override
    public R setTop(String id) {
        /*调用mapper接口*/
        baseMapper.setTopCollects(id);
        return R.ok();
    }

    /*解析token获得用户id*/
    private String parseToken2UserId(HttpServletRequest request) {
        /*获取token*/
        String token = request.getHeader("token");
        if (token == null) {
            throw new GlobalException(20002, "暂时未登录");
        }
        /*解析token*/
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("id");

    }
}

